
What is Loops?
Loops are a fundamental concept in programming that allows you to execute a set of instructions repeatedly for a specified number of times. They are used to simplify the code and make it more efficient.
There are three types of loops in JavaScript:
1. For loop
2. while loop
3. do-while loop
1. For Loop
The for loop is a control structure in JavaScript that allows you to execute a block of code a specific number of times. It is commonly used for iterating over arrays, performing calculations, or running repetitive tasks. It consists of three parts: initialization, condition, and increment.
Syntaxfor (initialization; condition; increment/decrement) {
// Code to execute on each iteration
}Explanation:
Example
for (let i = 1; i <= 5; i++) {
console.log("Count: " + i);
}a. Using a Decrementing Loop
You can count backward by decrementing the loop variable:
Explanation:
Example
for (let i = 5; i > 0; i--) {
console.log("Countdown: " + i);
}b. Skipping Iterations(continue)
The continue statement skips the rest of the code for the current iteration and moves to the next one:
Explanation:
Example
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue; // Skip iteration when i equals 3
}
console.log("Number: " + i);
}c. Breaking the Loop(break)
The break statement stops the loop completely:
Explanation:
Example
for (let i = 1; i <= 5; i++) {
if (i === 4) {
break; // Exit the loop when i equals 4
}
console.log("Number: " + i);
}